#!/usr/bin/env python
# coding: utf-8

import tt
import urlparse
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
    self.response.out.write('<h1>Hello, Barcamp Ghana 2009!</h1>')
    self.response.out.write('<a href="http://fusion.google.com/add?source=atgs&moduleurl=http%3A//barcampghana.appspot.com/igoogle"><img src="http://gmodules.com/ig/images/plus_google.gif" border="0" alt="Add to Google"></a><br/>')
    self.response.out.write(self._form(self.request.get('q'),
                                       self.vocabulary()))

    if self.request.get('q'):
      text = self.request.get('q')
    else:
      text = 'we love BarCampGhana'

    self.response.out.write('<h3>Example</h3><b>English</b>: %s<br/>' % text)
    from_lang = tt.detect_language(text)
    self.response.out.write('<b>Akan</b>: %s<br/>' %
                           self.translate(text, from_lang, 'ak'))

  def translate(self, text, from_language, to_language):
    return tt.translate(text, from_language, to_language)
  
  def vocabulary(self):
    return ', '.join(tt.dictionary('en', 'verb'))

  def _form(self, q, verbs, url='http://localhost:8080'):
    if url != 'http://localhost:8080':
      url = 'http://barcampghana.appspot.com'

    igoogle = iGoogle()
    return ('''
        <html>
          <body>
          <style>body{text-align:center; margin:0 auto;}
          #content_div {background-color:#ff0; -moz-border-radius:5px;
          -webkit-border-radius:5px;}</style>
          %s
            <form action="">
              <p>English: <input type="text" name="q" value="%s"/>
              <input type="submit" value="Translate" onClick="postUpdate(this.form); return false;"/>
              <br/>
              <small>Enter a simple statement with 3 words using the
              following verbs: %s</small>
              </p>
              <br/>
              Application URL: <input type="text" name="url" value="%s"/><br/>
              <small>For local testing this is usually
              <i>http://localhost:8080</i>. The live URL is
              <i>http://barcampghana.appspot.com</i>.</small>
            </form>
            <div id="content_div"></div>
          </body>
        </html>
        ''' % (igoogle.js(), q, verbs, url))


class iGoogle(webapp.RequestHandler):
  def __init__(self):
    self.page = MainPage()

  def get(self):
    if self.request.get('output') == 'json':
      self.response.out.write('getTranslation({\'translation\': \'%s\' })' %
                              self.page.translate(self.request.get('q'),
                                                  self.request.get('from'),
                                                  self.request.get('to')))
      return

    self.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
    self.response.out.write('''<?xml version="1.0" encoding="UTF-8" ?>
      <Module>
        <ModulePrefs title="Hello, Barcamp Ghana 2009!" author_email="pki@google.com" author="Paa Kwesi Imbeah">
          <Require feature="views" />
        </ModulePrefs>
        <Content type="html" view="home,profile,canvas">
          <![CDATA[
            %s
            %s
          ]]>
          
        </Content>
      </Module>
    ''' % (self.js(), self.page._form('i love BarCampGhana',
                                      self.page.vocabulary(),
                                      self.request.url[:-len(self.request.path)])))

  def js(self):
    js = ('''
          <script type="text/javascript">

  // Post an activity and set its title to be the text the user entered in the
  // text box.
  
  function jsonp(url,callback,name, query)
  {                
      if (url.indexOf("?") > -1)
          url += "&jsonp=" 
      else
          url += "?jsonp=" 
      url += name + "&";
      if (query)
          url += encodeURIComponent(query) + "&";   
      url += new Date().getTime().toString(); // prevent caching        
      
      var script = document.createElement("script");        
      script.setAttribute("src",url);
      script.setAttribute("type","text/javascript");                
      document.body.appendChild(script);
  }
  function getTranslation(Result){
    translated = Result.translation;
    var div = document.getElementById('content_div');
    div.innerHTML = "Akan: " + translated;
  }
  
  function postUpdate(form) { 
    var text = form.q.value;
    jsonp(form.url.value+'/igoogle?output=json&from=en&to=ak&q='+text);    
  }
  </script>
          ''')
    return js

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/igoogle', iGoogle)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
